package com.car.loan.project.ve.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.loan.common.enums.DeletedEnum;
import com.car.loan.common.enums.OperatorStatus;
import com.car.loan.common.utils.BeanUtils;
import com.car.loan.common.utils.StringUtils;
import com.car.loan.common.utils.qiniu.QiniuUtil;
import com.car.loan.framework.aspectj.lang.annotation.Log;
import com.car.loan.framework.aspectj.lang.enums.BusinessType;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.cd.domain.CdCredit;
import com.car.loan.project.cd.domain.vo.CreditAlbumVo;
import com.car.loan.project.cd.util.enums.CreditStatus;
import com.car.loan.project.ve.domain.VeVehicleAlbum;
import com.car.loan.project.ve.domain.VeVehicleEvaluation;
import com.car.loan.project.ve.domain.bo.VehicleEvaluationApplyAddBo;
import com.car.loan.project.ve.domain.bo.VehicleEvaluationApplyUpdateBo;
import com.car.loan.project.ve.domain.bo.VehicleEvaluationInputBo;
import com.car.loan.project.ve.domain.select.VehicleEvaluationBaseSelect;
import com.car.loan.project.ve.domain.vo.VehicleEvaluationApplyInfoVo;
import com.car.loan.project.ve.domain.vo.VehicleEvaluationBaseVo;
import com.car.loan.project.ve.domain.vo.VehicleEvaluationInputInfoVo;
import com.car.loan.project.ve.service.IVeVehicleAlbumService;
import com.car.loan.project.ve.service.IVeVehicleEvaluationService;
import com.car.loan.project.ve.util.enums.VehicleStatus;
import com.car.loan.project.xr.util.RedisDataUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author huangding
 * @description
 * @date 2019/10/29 22:07
 */
@RestController
@RequestMapping("ve")
@Api(value = "车辆评估管理", tags = "车辆评估管理")
public class VehicleEvaluationController {

    @Autowired
    private IVeVehicleEvaluationService veVehicleEvaluationService;

    @Autowired
    private IVeVehicleAlbumService veVehicleAlbumService;

    @Autowired
    private QiniuUtil qiniuUtil;

    @Autowired
    private RedisDataUtil redisDataUtil;

    @PreAuthorize("@ss.hasPermi('ve:apply:list')")
    @GetMapping("applyList")
    @ApiOperation(value = "车辆评估申请列表", responseContainer = "list", response = VehicleEvaluationBaseVo.class)
    public AjaxResult getApplyList(@Valid VehicleEvaluationBaseSelect vehicleEvaluationBaseSelect) {
        if (null == vehicleEvaluationBaseSelect.getStatus()) {
            vehicleEvaluationBaseSelect.setStatus(VehicleStatus.INIT.status);
        }
        if (VehicleStatus.COMPLETE.status == vehicleEvaluationBaseSelect.getStatus()) {
            LocalDate localDate = LocalDate.now().minusDays(60);
            vehicleEvaluationBaseSelect.setStartQueryDate(localDate.toString());
        }
        return AjaxResult
            .success(veVehicleEvaluationService
                .findVehicleEvaluationBasePage(vehicleEvaluationBaseSelect));
    }

    @PreAuthorize("@ss.hasPermi('ve:apply:query')")
    @GetMapping(value = "apply/{vehicleEvaluationId}")
    @ApiOperation(value = "获取车辆评估申请详情", response = VehicleEvaluationApplyInfoVo.class)
    public AjaxResult getApplyInfo(@PathVariable Long vehicleEvaluationId) {

        VeVehicleEvaluation veVehicleEvaluation = veVehicleEvaluationService
            .selectVeVehicleEvaluationById(vehicleEvaluationId);
        if (null == veVehicleEvaluation) {
            return AjaxResult.success("无该申请记录");
        }
        VehicleEvaluationApplyInfoVo vehicleEvaluationApplyInfoVo = new VehicleEvaluationApplyInfoVo();
        BeanUtils.copyBeanProp(vehicleEvaluationApplyInfoVo, veVehicleEvaluation);

        VeVehicleAlbum veVehicleAlbumQuery = new VeVehicleAlbum();
        veVehicleAlbumQuery.setVehicleId(vehicleEvaluationId);
        List<VeVehicleAlbum> veVehicleAlbums = veVehicleAlbumService
            .selectVeVehicleAlbumList(veVehicleAlbumQuery);

        if (StringUtils.isNotEmpty(veVehicleAlbums)) {
            List<CreditAlbumVo> imageAlbumVos = Lists.newArrayList();
            for (VeVehicleAlbum veVehicleAlbum : veVehicleAlbums) {
                imageAlbumVos.add(new CreditAlbumVo().setId(veVehicleAlbum.getId())
                    .setUrl(qiniuUtil.getAuthUrl(veVehicleAlbum.getUrl()))
                    .setThumbnailUrl(qiniuUtil.getUrlByThumbnailHttps(veVehicleAlbum.getUrl()))
                    .setDbUrl(veVehicleAlbum.getUrl()));
            }
            vehicleEvaluationApplyInfoVo.setImages(imageAlbumVos);
        }
        vehicleEvaluationApplyInfoVo
            .setAdminName(redisDataUtil.getAdminName(vehicleEvaluationApplyInfoVo.getAdminId()));
        vehicleEvaluationApplyInfoVo
            .setDeptName(redisDataUtil.getDeptName(vehicleEvaluationApplyInfoVo.getDeptId()));
        return AjaxResult.success(vehicleEvaluationApplyInfoVo);
    }


    @PreAuthorize("@ss.hasPermi('ve:apply:add')")
    @PostMapping("apply")
    @Log(title = "添加车辆评估", businessType = BusinessType.INSERT)
    @ApiOperation("添加车辆评估")
    public synchronized AjaxResult saveApply(
        @RequestBody @Valid VehicleEvaluationApplyAddBo vehicleEvaluationApplyAddBo) {
        vehicleEvaluationApplyAddBo
            .setFrameNo(vehicleEvaluationApplyAddBo.getFrameNo().toUpperCase());
        if (vehicleEvaluationApplyAddBo.getFrameNo().length() != 17) {
            return AjaxResult.error("车价号格式错误");
        }
        VeVehicleEvaluation veVehicleEvaluationQuery = new VeVehicleEvaluation();
        veVehicleEvaluationQuery.setFrameNo(vehicleEvaluationApplyAddBo.getFrameNo());
        QueryWrapper<VeVehicleEvaluation> queryWrapper = new QueryWrapper<>(
            veVehicleEvaluationQuery);
        queryWrapper.gt("create_time", LocalDateTime.now().minusDays(20));
        List<VeVehicleEvaluation> veVehicleEvaluations = veVehicleEvaluationService
            .selectVeVehicleEvaluationQueryList(queryWrapper);
        if (StringUtils.isNotEmpty(veVehicleEvaluations)) {
            return AjaxResult.error("该业务在20天内有重复申请，请联系管理员");
        }

        veVehicleEvaluationService.save(vehicleEvaluationApplyAddBo);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('ve:apply:edit')")
    @PutMapping("apply")
    @Log(title = "编辑车辆评估", businessType = BusinessType.UPDATE)
    @ApiOperation("编辑车辆评估")
    public synchronized AjaxResult editApply(
        @RequestBody @Valid VehicleEvaluationApplyUpdateBo vehicleEvaluationApplyUpdateBo) {
        vehicleEvaluationApplyUpdateBo
            .setFrameNo(vehicleEvaluationApplyUpdateBo.getFrameNo().toUpperCase());
        if (vehicleEvaluationApplyUpdateBo.getFrameNo().length() != 17) {
            return AjaxResult.error("车价号格式错误");
        }
        return veVehicleEvaluationService.update(vehicleEvaluationApplyUpdateBo);
    }


    @PreAuthorize("@ss.hasPermi('ve:apply:withdraw')")
    @PutMapping("apply/withdraw/{vehicleEvaluationId}")
    @Log(title = "撤回车辆评估申请", businessType = BusinessType.WITHDRAW)
    @ApiOperation(value = "撤回车辆评估申请", notes = "不可撤回，status=10")
    public AjaxResult withdrawApply(@PathVariable Long vehicleEvaluationId) {
        VeVehicleEvaluation veVehicleEvaluation = veVehicleEvaluationService
            .selectVeVehicleEvaluationById(vehicleEvaluationId);
        if (null == veVehicleEvaluation) {
            return AjaxResult.error("无该申请信息");
        }
        if (VehicleStatus.SUBMIT.status != veVehicleEvaluation.getStatus()) {
            return AjaxResult.error("当前状态不可撤回");
        }
        veVehicleEvaluation.setStatus(VehicleStatus.INIT.status);
        veVehicleEvaluationService.updateVeVehicleEvaluation(veVehicleEvaluation);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('ve:album:delete')")
    @DeleteMapping("album/{albumId}")
    @Log(title = "车辆评估附件删除", businessType = BusinessType.DELETE)
    @ApiOperation("车辆评估附件删除")
    public AjaxResult creditAlbumDelete(@PathVariable Long albumId) {
        veVehicleAlbumService.deleteVeVehicleAlbumById(albumId);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('ve:apply:delete')")
    @DeleteMapping("apply/{vehicleEvaluationId}")
    @Log(title = "车辆评估申请删除", businessType = BusinessType.DELETE)
    @ApiOperation("征信申请删除")
    public AjaxResult creditDelete(@PathVariable Long vehicleEvaluationId) {
        VeVehicleEvaluation veVehicleEvaluation = veVehicleEvaluationService
            .selectVeVehicleEvaluationById(vehicleEvaluationId);
        if (veVehicleEvaluation == null) {
            return AjaxResult.error("不存在");
        }
        if (VehicleStatus.INIT.status == veVehicleEvaluation.getStatus()
            || VehicleStatus.REVOKE.status == veVehicleEvaluation.getStatus()) {
            veVehicleEvaluation.setDeleted(DeletedEnum.DELETED.getCode());
            veVehicleEvaluationService.updateVeVehicleEvaluation(veVehicleEvaluation);
            return AjaxResult.success();
        }
        return AjaxResult.error("当前状态不可删除");
    }


    @PreAuthorize("@ss.hasPermi('ve:input:list')")
    @GetMapping("inputList")
    @ApiOperation(value = "车辆评估录入列表", responseContainer = "list", response = VehicleEvaluationBaseVo.class)
    public AjaxResult getInputList(@Valid VehicleEvaluationBaseSelect vehicleEvaluationBaseSelect) {
        if (null == vehicleEvaluationBaseSelect.getStatus()) {
            vehicleEvaluationBaseSelect.setStatus(VehicleStatus.SUBMIT.status);
        }
        return AjaxResult
            .success(veVehicleEvaluationService
                .findVehicleEvaluationBasePage(vehicleEvaluationBaseSelect));
    }

    @PreAuthorize("@ss.hasPermi('ve:input:query')")
    @GetMapping(value = "input/{vehicleEvaluationId}")
    @ApiOperation(value = "获取车辆评估录入详情", response = VehicleEvaluationInputInfoVo.class)
    public AjaxResult getInputInfo(@PathVariable Long vehicleEvaluationId) {

        VeVehicleEvaluation veVehicleEvaluation = veVehicleEvaluationService
            .selectVeVehicleEvaluationById(vehicleEvaluationId);
        if (null == veVehicleEvaluation) {
            return AjaxResult.success("无该申请记录");
        }
        VehicleEvaluationInputInfoVo vehicleEvaluationInputInfoVo = new VehicleEvaluationInputInfoVo();
        BeanUtils.copyBeanProp(vehicleEvaluationInputInfoVo, veVehicleEvaluation);

        vehicleEvaluationInputInfoVo
            .setInputAdminName(redisDataUtil.getAdminName(veVehicleEvaluation.getInputAdminId()));
        vehicleEvaluationInputInfoVo
            .setSubmitAdminName(redisDataUtil.getAdminName(veVehicleEvaluation.getSubmitAdminId()));

        VeVehicleAlbum veVehicleAlbumQuery = new VeVehicleAlbum();
        veVehicleAlbumQuery.setVehicleId(vehicleEvaluationId);
        List<VeVehicleAlbum> veVehicleAlbums = veVehicleAlbumService
            .selectVeVehicleAlbumList(veVehicleAlbumQuery);

        if (StringUtils.isNotEmpty(veVehicleAlbums)) {
            List<CreditAlbumVo> imageAlbumVos = Lists.newArrayList();
            for (VeVehicleAlbum veVehicleAlbum : veVehicleAlbums) {
                imageAlbumVos.add(new CreditAlbumVo().setId(veVehicleAlbum.getId())
                    .setUrl(qiniuUtil.getAdminAuthUrl(veVehicleAlbum.getUrl()))
                    .setThumbnailUrl(qiniuUtil.getUrlByThumbnail(veVehicleAlbum.getUrl()))
                    .setDbUrl(veVehicleAlbum.getUrl()));
            }
            vehicleEvaluationInputInfoVo.setImages(imageAlbumVos);
        }
        Integer status = vehicleEvaluationInputInfoVo.getStatus();
        if (status == VehicleStatus.SUBMIT.status) {
            vehicleEvaluationInputInfoVo.setOperatorStatus(OperatorStatus.SAVE.status);
        } else if (status == VehicleStatus.COMPLETE.status) {
            vehicleEvaluationInputInfoVo.setOperatorStatus(OperatorStatus.SUBMIT.status);
        } else if (status == VehicleStatus.REVOKE.status) {
            vehicleEvaluationInputInfoVo.setOperatorStatus(OperatorStatus.REVOKE.status);
        }
        vehicleEvaluationInputInfoVo
            .setInputAdminName(redisDataUtil.getAdminName(veVehicleEvaluation.getInputAdminId()));
        vehicleEvaluationInputInfoVo.setInputTime(veVehicleEvaluation.getInputTime());
        vehicleEvaluationInputInfoVo
            .setAdminName(redisDataUtil.getAdminName(vehicleEvaluationInputInfoVo.getAdminId()));
        vehicleEvaluationInputInfoVo
            .setDeptName(redisDataUtil.getDeptName(vehicleEvaluationInputInfoVo.getDeptId()));
        return AjaxResult.success(vehicleEvaluationInputInfoVo);
    }


    @PreAuthorize("@ss.hasPermi('ve:input:edit')")
    @PutMapping("input")
    @Log(title = "车辆评估录入", businessType = BusinessType.UPDATE)
    @ApiOperation("车辆评估录入")
    public synchronized AjaxResult editInput(
        @Valid @RequestBody VehicleEvaluationInputBo vehicleEvaluationApplyUpdateBo) {
        return veVehicleEvaluationService.input(vehicleEvaluationApplyUpdateBo);
    }

    @PreAuthorize("@ss.hasPermi('ve:input:withdraw')")
    @PutMapping("input/withdraw/{vehicleEvaluationId}")
    @Log(title = "撤回车辆评估录入", businessType = BusinessType.WITHDRAW)
    @ApiOperation(value = "撤回车辆评估")
    public AjaxResult withdrawInput(@PathVariable Long vehicleEvaluationId) {
        VeVehicleEvaluation veVehicleEvaluation = veVehicleEvaluationService
            .selectVeVehicleEvaluationById(vehicleEvaluationId);
        if (null == veVehicleEvaluation) {
            return AjaxResult.error("无该申请信息");
        }
        if (VehicleStatus.COMPLETE.status != veVehicleEvaluation.getStatus()) {
            return AjaxResult.error("当前状态不可撤回");
        }
        veVehicleEvaluation.setStatus(VehicleStatus.SUBMIT.status);
        veVehicleEvaluationService.updateVeVehicleEvaluation(veVehicleEvaluation);
        return AjaxResult.success();
    }


}
